﻿# encoding: 'utf-8'
import base64
#from test_client2 import *
import flask
from flask import request, Flask
import datetime
from logging.handlers import TimedRotatingFileHandler
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
#from mysql_util import Database
import cv2
import time

# 图片命名规则：No_条码(sn)_检测结果_年月日-时分秒.jpg(1MB内)
# 设置连接数据库的参数
# config = {
#     "host": "127.0.0.1",
#     "port": 3306,
#     "database": "midea",
#     "charset": "utf8",
#     "user": "root",
#     "passwd": "1q2w3e"
# }
month_list = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

app = Flask(__name__)
# detect = Detection()
pool = ThreadPoolExecutor(max_workers=64)


def test_update(imgs, product, save_path, end, adress):
    import random

    random = random.randint(1000000, 9999999)
    random = str(random)

    destImg_base64 = imgs
    try:
        today = datetime.datetime.today()
        year = str(today.year)
        mounth = str(today.month)
        day = str(today.day).zfill(2)
        TIME_ID = time.strftime('%Y%m%d-%H%M%S', time.localtime(time.time()))
        destImg = base642im(destImg_base64)
        photoname = f'No_{product}_{end}_{TIME_ID}_{random}.jpg'
        a = os.path.join(save_path, photoname)
        #logger.info('test_update save', a)
        with open(a, 'wb') as f:
            f.write(destImg)
            f.close()

        u = 'http://10.177.8.51:8000/data'
        url = os.path.join(u, year, mounth.zfill(2), day, photoname)  # ip加上后期作为更新界面的信号
        url = url.replace('\\', '/')
        tables = year + month_list[int(mounth) - 1]

        # db = Database(**config)
        # db.new_tables(tables)
        # db.insert(tables, (0, product, end, url, TIME_ID, adress))
        return url

    except Exception as e:
        logger.info(f'test_update {str(e)}')
        return 0


def base642im(img_str):
    # 此时可以测试解码得到图像并显示，服务器端也按照下面的方法还原图像继续进一步处理
    img_decode_ = img_str.encode('ascii')  # ascii编码
    img_decode = base64.urlsafe_b64decode(img_decode_)  # base64解码

    return img_decode


def write(path, img):
    cv2.imwrite(path, img)


def setLog(port):
    log_fmt = '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'
    formatter = logging.Formatter(log_fmt)
    t = str(time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()))
    fh = TimedRotatingFileHandler(
        filename="run_facefusion_server_%s_%d.log" % (t, port),
        when="H", interval=1,
        backupCount=72)
    fh.setFormatter(formatter)
    logging.basicConfig(level=logger.info)
    log = logging.getLogger()
    log.addHandler(fh)


# 定义路由

def get_outpa():
    for d in 'YEDFC':
        pa = f'{d}'
        if os.path.exists(f"{d}:/"):
            pa = f'{d}:/data'
            #mkdir(pa)
            return pa
    
    return pa

@app.route("/ai/v1/mdzx_detect", methods=['POST'])
def get_frame():
    res = []
    try:
        today = datetime.datetime.today()
        year = str(today.year)
        mounth = str(today.month)
        day = str(today.day).zfill(2)
        start_time = time.time()
        resParm = flask.request.data
        ip = request.remote_addr
        # 转字符串``
        resParm = str(resParm, encoding="utf-8")
        resParm = eval(resParm)
        adress = resParm["class"]
        end = resParm["end"]
        product = resParm["product"]
        pa = get_outpa()
        root_time_path = f'{pa}/{year}/{mounth}/{day}/{product}'
        product = product.strip()
        # save_path = os.path.join(root_time_path, year,mounth,day,product)
        os.makedirs(root_time_path, exist_ok=True)
        # 按照debase64进行处理
        for i, key in enumerate(resParm.keys()):
            if key == 'product' or key == 'class' or key == 'end':
                continue
            imgs = resParm["images"]
            lst_value = []
            result = []
            lis = []
            for value in imgs.items():
                lst_value.append(value)
            for n in range(len(imgs)):
                name, img = lst_value[n]
                a = pool.submit(test_update, img, product, root_time_path, end, adress)
                result.append(a)

            for massion in as_completed(result):

                a = str(massion.result())
                if a != '0':
                    lis.append(a)
            # res = qms_client(product, adress, end, lis)
            res = 'ok'
            print(res, '\r\n', adress, ip, product, '\r\n', '\r\n', '\r\n')
            
        if res is not None:
            rs = {
                'code': 0,
                'res': res
            }
        else:
            rs = {'code': 7}
        x1 = time.time()
        x = x1 - start_time
        print('get_frame:', x)
        return rs

    except Exception as x:
        print("ERROR:", x)
        logging.exception(x)
        res = {'code': 7}
        print('ng')
        return res


def main(host, port, processes):
    app.run(host=host, port=port, processes=processes)


if __name__ == "__main__":
    host='10.177.8.51'
    host = '192.168.12.73'
    host = '127.0.0.1'
    main(host=host, port=5000, processes=False)
